package com.qiaoanju.web.security.service;

import com.qiaoanju.back.domain.system.MenuModel;
import com.qiaoanju.back.domain.system.RoleModel;
import com.qiaoanju.back.domain.system.UserModel;
import com.qiaoanju.back.dto.system.UserDto;
import com.qiaoanju.back.service.system.IGroupService;
import com.qiaoanju.back.service.system.IMenuService;
import com.qiaoanju.back.service.system.IRoleService;
import com.qiaoanju.back.service.system.IUserService;
import com.qiaoanju.commons.constants.StringConstant;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by eversec
 * on 2017/9/22.
 */
@Service("customUserDetailsService")
public class CustomUserDetailsService implements UserDetailsService {

    private static final Logger logger = LogManager.getLogger();
    @Autowired
    private IUserService userService ;

    @Autowired
    private IMenuService menuService ;

    @Autowired
    private IGroupService groupService ;

    @Autowired
    private IRoleService roleService ;


    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        logger.info("######################loadUserByUsername%%%%%%%%%%%" +username);
        //根据登录名获取登陆用户
        UserDto loginUser =  userService.getLoginUserByUsername(username);
        List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
        if(loginUser != null){


            //设置用户信息
            int groupId = loginUser.getGroup_id() ;
            if(groupId== 1){//管理员用户

                if(loginUser.getUser_type() == 1){//leader

                    List<MenuModel> allMenus = menuService.getAllMenus(0);
                    loginUser.setMenuPackage(allMenus);
                }

                //获取角色信息
                List<RoleModel> allRole = roleService.getRoleByGroupId(groupId);
                loginUser.setRolePackage(allRole);
                //展示角色
                loginUser.setCore_role_name(allRole.get(0).getRole_name());

            }else{//其他部门

            }

            //分配权限
            if (loginUser.getUser_type() == 1){

                authorities.add(new SimpleGrantedAuthority(StringConstant.ROLE_ADMIN));
            }else{
                authorities.add(new SimpleGrantedAuthority(StringConstant.ROLE_USER));
            }
            loginUser.setAuthorities(authorities);
        }

        return loginUser ;
    }
/*	@Override
	public UserDetails loadUserByUsername2(String username) throws UsernameNotFoundException {
		System.out.println("######################loadUserByUsername%%%%%%%%%%%");
		//根据登录名获取登陆用户
		UserModel user = userService.getUserByUsername(username);
		if(user == null){
			throw new UsernameNotFoundException("用户" + username + "不存在");
		}
		GroupModel group = groupService.getGroupById(user.getGroup_id());
		//根据用户的 类型获取用户权限

		//用户类型为0, 表示是系统平台管理员用户

		//团队管理员

		//团队用户


		//根据用户的 类型获取用户权限
        if(user.getUser_type() == UserType.SysAdmin.getValue()){ //用户类型为0, 表示是系统平台管理员用户
            Collection<GrantedAuthority> auths = new ArrayList<GrantedAuthority>();
			Map<String ,Object> map = new HashMap<>();
            List<RoleModel> authorities = map.get("roles");  //获取系统中所有权限
            for(Iterator<Authority> iter =authorities.iterator();iter.hasNext();){
                auths.add(new SimpleGrantedAuthority(iter.next().getCode()));
            }
            //UserDetail userDetail =  new UserDetail(userName, user.getPassword(), true, true, true, true, auths);
            //修改为前台系统，不能让系统管理员登陆
            UserDetail userDetail =  new UserDetail(userName, user.getPassword(), false, true, true, true, auths);
            userDetail.setUserGroupId(user.getUserGroup().getId());
            userDetail.setRealName(user.getRealName());
            userDetail.setUserType(user.getUserType());
            return userDetail;
        }else if(user.getUserType() == UserType.TeamAdmin){ //团队管理员
            //用户是否可用
            boolean enabled = user.getEnabled();
            //获取团队管理员的所有权限
            Set<Authority> authorities = user.getAuthoritySet();
            Collection<GrantedAuthority> auths = new ArrayList<GrantedAuthority>();
            for(Iterator<Authority> iter=authorities.iterator();iter.hasNext();){
                auths.add(new SimpleGrantedAuthority(iter.next().getCode()));
            }
            //因为spring security包中的User也实现了UserDetails，所以也可以直接返回User
            UserDetail userDetail =null;
            if(UserState.Enable == user.getUserState()){
                userDetail = new UserDetail(userName, user.getPassword(), enabled, true, true, true, auths);
            }else{
                userDetail = new UserDetail(userName, user.getPassword(), enabled, true, true, false, auths);
                //throw new LockedException("用户" + userName + "被锁定");
            }
            userDetail.setUserGroupId(user.getUserGroup().getId());
            userDetail.setTeamGroupId(user.getUserGroup().getId());
            userDetail.setRealName(user.getRealName());
            userDetail.setUserType(user.getUserType());
            return userDetail;

        }else{//团队用户
            //用户是否可用
            boolean enabled = user.getEnabled();
            Set<Authority> authorities = user.getAuthoritySet();
            Collection<GrantedAuthority> auths = new ArrayList<GrantedAuthority>();
            for(Iterator<Authority> iter=authorities.iterator();iter.hasNext();){
                auths.add(new SimpleGrantedAuthority(iter.next().getCode()));
            }
            //因为spring security包中的User也实现了UserDetails，所以也可以直接返回User
            UserDetail userDetail =null;

            if(user.getUserGroup().getTeamAdmin().getUserState()==UserState.Disable){//如果团队管理员被禁用，其下属团队用也不能登录
                userDetail = new UserDetail(userName, user.getPassword(), enabled, true, true, false, auths);
                return userDetail;
            }

            if(UserState.Enable == user.getUserState()){
                userDetail = new UserDetail(userName, user.getPassword(), enabled, true, true, true, auths);
            }else{
                userDetail = new UserDetail(userName, user.getPassword(), enabled, true, true, false, auths);
                //throw new LockedException("用户" + userName + "被锁定");
            }
            userDetail.setUserGroupId(user.getUserGroup().getId());
            userDetail.setTeamGroupId(user.getUserGroup().getTeamAdmin().getUserGroup().getId());
            userDetail.setRealName(user.getRealName());
            userDetail.setUserType(user.getUserType());
            return userDetail;

        }
		Collection<GrantedAuthority> auths = new ArrayList<GrantedAuthority>();
		return new UserDetail(user.getUsername(),user.getPassword(),auths);

    }*/

}

